package com.smartkey.activity;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.widget.Toast;

import com.project.smartkey.R;
import com.smartkey.utils.DateUtils;
import com.smartkey.utils.SDCardUtils;

public class TakePhotoActivity extends BaseActivity {

	private int takephoto = 0x10001;
	String fileName;
	String filePath;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sk_activity_takephoto);
		if (!SDCardUtils.isSDCardAvaliable()) {
			Toast.makeText(this, "SDCard不可用", Toast.LENGTH_SHORT).show();
			finish();
		}
		startTakePhoto();
	}

	private void startTakePhoto() {
		String photoDir = Environment.getExternalStorageDirectory()
				+ File.separator + Environment.DIRECTORY_DCIM;
		fileName = DateUtils.getCurrentDateStr(DateUtils.format1) + ".JPEG";
		filePath = photoDir + File.separator + fileName;
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT,
				Uri.fromFile(new File(fileName)));
		startActivityForResult(intent, takephoto);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (takephoto == requestCode && RESULT_OK == resultCode) {// 处理系统拍摄的照片
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inTempStorage = new byte[1024 * 1024 * 3];
			// options.inSampleSize = 2;
			Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
			// Bitmap bm = (Bitmap) data.getExtras().get("data");
			File myCaptureFile = new File(MediaStore.EXTRA_OUTPUT
					+ File.separator + fileName);
			try {

				BufferedOutputStream bos = new BufferedOutputStream(
						new FileOutputStream(myCaptureFile));
				/* 采用压缩转档方法 */
				bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);

				/* 调用flush()方法，更新BufferStream */
				bos.flush();

				/* 结束OutputStream */
				bos.close();
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
		super.onActivityResult(requestCode, resultCode, data);
		finish();
	}
}
